package com.itfreer.file.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import com.itfreer.file.FileSegmentInfo;
import com.itfreer.utils.json.JsonUtils;

/**
 * 对象下载接口
 */
@Component
@Path("/file/objectDownloadService")
public class ObjectDownloadService {

	@Autowired
	private IObjectDownloadService objectDownload;
	
	/**
	 * 获取对象
	 * @param bucketName		存储块名称
	 * @param objectKey		对象名称主键
	 */
	@GET
    @Path("/download")
	@Produces({MediaType.APPLICATION_OCTET_STREAM})
	public Response download(@QueryParam("bucketName") String bucketName, 
			@QueryParam("objectKey") String objectKey){
		byte[] result = objectDownload.getObject(bucketName, objectKey);
		StreamingOutput stream = new StreamingOutput() {
			@Override
			public void write(OutputStream output) throws IOException, WebApplicationException {
				try {
					output.write(result);
	            } catch (Exception e) {
	                throw new WebApplicationException(e);
	            }
			}
	    };
	    return Response.ok(stream)
	    		.header("content-disposition","attachment;")
	    		.header("Cache-Control", "no-cache").build();
	}
	
	/**
	 * 获取对象
	 * @param bucketName		存储块名称
	 * @param objectKey		对象名称主键
	 */
	@GET
    @Path("/getObject")
	@Produces({MediaType.APPLICATION_OCTET_STREAM})
	public Response getObject(@QueryParam("bucketName") String bucketName, 
			@QueryParam("objectKey") String objectKey){
		byte[] result = objectDownload.getObject(bucketName, objectKey);
		StreamingOutput stream = new StreamingOutput() {
			@Override
			public void write(OutputStream output) throws IOException, WebApplicationException {
				try {
					output.write(result);
	            } catch (Exception e) {
	                throw new WebApplicationException(e);
	            }
			}
	    };
	    return Response.ok(stream)
	    		.header("content-disposition","attachment;")
	    		.header("Cache-Control", "no-cache").build();
	}
	
	/**
	 * 断点续传下载
	 * @param bucketName		存储块名称
	 * @param objectKey			对象存储key
	 * @param segmentInfo		分段信息
	 */
	@GET
    @Path("/downloadFile")
	@Produces(MediaType.APPLICATION_JSON)
	public String downloadFile(@QueryParam("bucketName") String bucketName, 
			@QueryParam("objectKey") String objectKey, 
			@QueryParam("segmentInfo") String segmentInfo){
		FileSegmentInfo info = null;
		try {
			info = JsonUtils.toBean(segmentInfo, FileSegmentInfo.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		FileSegmentInfo result = objectDownload.downloadFile(bucketName, objectKey, info);
		return JsonUtils.toJSONString(result);
	}
}
